package com.stars.easyms.rest.handler;

import com.stars.easyms.base.util.ApplicationContextHolder;
import com.stars.easyms.rest.ResponseEntityHandler;
import com.stars.easyms.rest.bean.EasyMsRestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;

/**
 * <p>className: ResponseEntityHandlerFactory</p>
 * <p>description: ResponseEntityHandler工厂类</p>
 *
 * @author guoguifang
 * @version 1.7.1
 * @date 2020/12/11 8:07 下午
 */
@Slf4j
@SuppressWarnings("unchecked")
final class ResponseEntityHelper {

    private static ResponseEntityHandler responseEntityHandler;

    static {
        ResponseEntityHandler localResponseEntityHandler = ApplicationContextHolder.getBean(ResponseEntityHandler.class);
        responseEntityHandler = localResponseEntityHandler != null ? localResponseEntityHandler : new EasyMsResponseEntityHandler();
    }

    static Object getResponseEntity(@NonNull EasyMsRestContext easyMsRestContext) {
        Object responseEntity = null;
        Object responseBody = easyMsRestContext.getResponseBody();
        Throwable throwable = easyMsRestContext.getThrowable();
        // 由于responseEntityHandler可能为自定义的，所以可能出现异常
        try {
            if (responseBody == null && throwable != null) {
                responseEntity = responseEntityHandler.getResponseEntityWithException(throwable);
                easyMsRestContext.setResponseBodyWithThrowable(true);
            } else {
                responseEntity = responseEntityHandler.getResponseEntity(responseBody);
            }
        } catch (Exception e) {
            log.error("Get response entity fail!", e);
        }
        easyMsRestContext.setResponseEntity(responseEntity);
        easyMsRestContext.setReturnResponseBody(true);
        return responseEntity;
    }

    private ResponseEntityHelper() {
    }
}
